import React, { useEffect } from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { Provider } from 'mobx-react';
import store, { useStore } from './store';
import { useLocation, useHistory } from 'react-router';
import { BrowserRouter } from 'react-router-dom';
import { reaction } from 'mobx';

function TabObserver() {
  const history = useHistory();
  const location = useLocation();
  const { UIState } = useStore();
  useEffect(() => {
    UIState.setActiveTabWithGuard(location, async () => {
      const whiteLocationList = new Set(['/', '/page1', '/page2']);
      if (!whiteLocationList.has(location.pathname)) {
        history.replace(
          UIState.getTabUrl(UIState.currentTab || { pathname: '/' })
        );
        return Promise.reject();
      }
    });
  }, [UIState, history, location]);
  useEffect(() => {
    let dispose = reaction(
      () => ({
        currentTab: UIState.currentTab,
      }),
      () => {
        if (UIState.currentTab == null) {
          UIState.setActiveTab(UIState.fallbackTab);
        } else {
          const curUrl = UIState.tabToUrl(history.location);
          if (UIState.currentTabUrl !== curUrl) {
            if (UIState.isTabEqual(history.location, UIState.currentTab)) {
              history.replace(UIState.currentTabUrl);
            } else {
              history.push(UIState.currentTabUrl);
            }
          }
        }
      }
    );
    return () => {
      dispose();
    };
  }, [UIState, history]);
  return null;
}

ReactDOM.render(
  // <React.StrictMode>
  //   <App />
  // </React.StrictMode>,
  <Provider {...store}>
    <BrowserRouter>
      <App />
      <TabObserver />
    </BrowserRouter>
  </Provider>,
  document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
